// pages/mine/info/user.js
const App = getApp()
import Qiniu from '../../../utils/qiniu'

Page({
  data: {
    init: false,

    user: {},
  },
  onLoad() {
    wx.sub('ReloadUserInfo', this, () => {
      this.execLoad()
    })
    this.execLoad()
  },
  onUnload() {
    wx.cancel('ReloadUserInfo', this)
  },
  execLoad() {
    App.doPost({
      uri: '/app/user/info/profile/info',
      body: {},
      fnSucc: resp => {
        this.setData({
          init: true,
          user: resp.data
        })
      }
    })
  },
  toPage(e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.uri
    })
  },
  doSelectAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      camera: 'front',
      success: (res) => {
        this.execUpload(res.tempFiles[0].tempFilePath)
      }
    })
  },
  execUpload(path) {
    App.doPost({
      uri: '/comm/tool/file/qiniu/info',
      body: {
        type: 'Image'
      },
      fnSucc: resp => {
        let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
        Qiniu.upload(path, (res) => {
          App.doPost({
            uri: '/app/user/info/profile/avatar',
            body: {
              avatar: res.imageURL
            },
            fnSucc: () => {
              wx.pub("ReloadUserInfo", {})
            }
          })

        }, (err) => {
          console.log(err)
        }, {
          region: 'NCN',
          key: key,
          uptoken: resp.data.token,
          uptokenFunc: null,
          uptokenURL: null,
          domain: resp.data.domain,
          shouldUseQiniuFileName: false,
        }, (progress) => {
          this.setData({
            progress
          })
          // console.log('上传进度', progress.progress);
          // console.log('已经上传的数据长度', progress.totalBytesSent);
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend);
        }, (cancel) => {
          this.setData({
            cancel
          })
        })
      },
      fnFail: resp => {
        App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
      }
    })
  },
})